var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var loginRouter = require('./routes/login');
var uploadRouter = require('./routes/upload');
var jwt = require('./util/JWT')

//引入express-session
var session = require('express-session');
var MongoStore = require('connect-mongo')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


//使用Token校验,所以不需要seeion校验了
//注册session中间件,判断session和cookie是否关联,用来判断是否有权限进入后台页面
// app.use(session({
//   name: "yun",             //设置session名称
//   secret: "yun",        
//   cookie: {
//     maxAge: 1000*60*60,    //设置session过期时间
//     secure: false,         //secure设置为true,表示只能https才能访问cookie
//   },
//   resave: true,            //只有重新设置session,才会重新设置过期时间
//   saveUninitialized: true,  //初始时设置一个cookie
//   //将数据存储到数据库中
//   store: MongoStore.create({
//     mongoUrl: 'mongodb://127.0.0.1:27017/Yun_session',   //创建数据库
//     ttl: 1000*60*60   //过期时间
//   })
// }))


//设置中间件,session过期校验
app.use((req,res,next)=>{
  if(req.url.includes('/login')){
    next();
    return
  }
  
  //判断是否登录
  // if(req.session.user){
  //   //重新设置一下session
  //   req.session.mydata = Date.now()
  //   next();
  // }else{
  //   //未登录,重定向到登录页面
  //   //是接口 返回错误码
  //   //不是接口,就重定向
  //   req.url.includes('/api')?res.status(401).json({ok:0}):res.redirect('/login');
    
  // }
  //判断token
  const token = req.headers['authorization']?.split(" ")[1]
  console.log(token)
  if(token){
    const payload = jwt.verify(token,'secret')
    if(payload){
      //重新计算token过期时间
      const newToken= jwt.generate({
        _id: payload._id,
        username: payload.username
      },'1h')
      res.header('Authorization',newToken)
      next()
    }else{
      res.status(401).send({errCode: -1, errInfo: 'token过期'})
    }
  }else{
    next();
  }
 
  
})

app.use('/', indexRouter);
app.use('/api', usersRouter);
app.use('/login',loginRouter)
app.use('/upload',uploadRouter)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
